/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Persistencia.Archivo;
import client.MailClient;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import server.MailServer;

/**
 *  Login representa la interfaz grafica para autenticarse e iniciar session en un servidor.
 * @author Jhonny
 */
public class Login extends javax.swing.JFrame {
    public static Archivo archivoServidores;
    public static MailServer serverActivo;
    public static MailClient clienteActivo;
    public static ArrayList<MailServer> servidores;
    public static Cliente formularioCliente;
    public static CrearServer formularioServidor;
    public static Login principalActivo;
    public static ListarUsuario formularioListadoUsuarios;
    public static NuevoUsuario formularioCreacionUsuario;
    
    /**
     * Constructor de la clase Login.
     * Creates new form Login
     */
    public Login() {
        initComponents();        
        this.setSize(450, 350);
        this.setLocationRelativeTo(null);
        principalActivo = this;
        archivoServidores = new Archivo("Servidores", "servers.zajod");
        servidores = (ArrayList<MailServer>)archivoServidores.leer();
        actualizarVista(); 
        jtxtUsuario.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e){
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    Login.this.bntIngresarActionPerformed(null);
                }
            }
        });
    }
    /**
     * Metodo que instacia a la clase Login.
     * @return una instancia de la clase Login. 
     */
    public static Login getInstance(){
        return principalActivo;
    }
    /**
     * Actualiza la lista de servidores listando todos los servidores registrados.
     */
    public void actualizarVista(){
        if (servidores == null) {
            servidores = new ArrayList<>();
        }
        jcbServidores.removeAllItems();
        for (int i = 0; i < servidores.size(); i++) {
            jcbServidores.addItem(servidores.get(i));
        }
    }
    
    public byte[] convertirFileToByteArray(File file){
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bFile = new byte[(int) file.length()];
            fileInputStream.read(bFile);
            fileInputStream.close();
           return bFile;
        } catch (Exception e) {
            return null;
        }
   }
        
    public File convertirArrayByteToFile(byte[] bytes){
        try {
            File result = new File("D:\\testing3.txt");
            FileOutputStream fileOuputStream =  new FileOutputStream(result); 
            fileOuputStream.write(bytes);
            fileOuputStream.close();
            return result;
        } catch (Exception e) {
            return null;
        }
    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jtxtUsuario = new javax.swing.JTextField();
        bntIngresar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jcbServidores = new javax.swing.JComboBox();
        btnAdministrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(null);

        jPanel1.setBackground(new java.awt.Color(0, 153, 153));
        jPanel1.setLayout(null);
        jPanel1.add(jtxtUsuario);
        jtxtUsuario.setBounds(50, 50, 220, 40);

        bntIngresar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bntIngresar.setText("Ingresar");
        bntIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntIngresarActionPerformed(evt);
            }
        });
        jPanel1.add(bntIngresar);
        bntIngresar.setBounds(20, 190, 110, 40);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Usuario");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(50, 20, 80, 30);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Server");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(50, 94, 90, 30);

        jcbServidores.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jcbServidores.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jPanel1.add(jcbServidores);
        jcbServidores.setBounds(50, 130, 230, 40);

        btnAdministrar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        btnAdministrar.setText("Administrar");
        btnAdministrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdministrarActionPerformed(evt);
            }
        });
        jPanel1.add(btnAdministrar);
        btnAdministrar.setBounds(160, 190, 140, 40);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(30, 29, 350, 240);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bntIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntIngresarActionPerformed
        // TODO add your handling code here:
        String userName = jtxtUsuario.getText();
        MailServer serverElegido = (MailServer)jcbServidores.getSelectedItem();
        if (serverElegido.usuarioValido(userName)) {
            serverActivo = serverElegido;
            clienteActivo = new MailClient(userName, serverActivo);
            formularioCliente = new Cliente(clienteActivo);
            this.setVisible(false);
            formularioCliente.setVisible(true);
        }else{
            JOptionPane.showMessageDialog(null, "Usuario igresado no esta registrado en este servidor");
        }
    }//GEN-LAST:event_bntIngresarActionPerformed

    private void btnAdministrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdministrarActionPerformed
        // TODO add your handling code here:
        formularioServidor = new CrearServer();
        this.setVisible(false);
        formularioServidor.setVisible(true);
    }//GEN-LAST:event_btnAdministrarActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        archivoServidores.escribir(servidores);
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntIngresar;
    private javax.swing.JButton btnAdministrar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JComboBox jcbServidores;
    private javax.swing.JTextField jtxtUsuario;
    // End of variables declaration//GEN-END:variables
}
